package pld.car.action;

import java.io.File;
import java.io.InputStream;
import java.util.*;
import pld.car.bean.News;
import pld.car.bean.NewsImg;
import pld.car.utils.Public;

public class ManageNewsAction extends BaseAction {

	private List<Object> newsList;

	private int rowCountPerPage;

	private int maxPageInBar;

	private String pageBar;

	private int pageNo;

	private String ids;

	private int newsID;

	private String rte;
	private String result;

	private InputStream imageStream;

	// ===========新增新闻所需变量==================
	private News news;
	private File[] image;
	private String[] imgTitle;
	private String[] imgNote;
	private Date createDate;
	// ============================================
	// ===========修改新闻所需变量==================
	private List<Integer> imgDel;
	private int imgID;

	// ===========修改新闻内容所需变量==================
	private String newsContent;

	public ManageNewsAction() {
		System.out.println("ManageNewsAction init!");
	}

	// ========================================================================================================
	// ============================================新闻管理====================================================
	// ========================================================================================================

	// ===========================增加新闻=============================================
	// 增加新闻
	public String addNews() {
		try {
			insertNews();
		} catch (Exception e) {
			System.out.println("新闻保存失败。");
			e.printStackTrace();
		} finally {
			clearIt();
		}
		return "success";
	}

	// 插入记录
	public String insertNews() throws Exception {
		Set<NewsImg> imgSet = new LinkedHashSet<NewsImg>();
		if (this.getImage() != null) {
			for (int i = 0; i < this.getImage().length; i++) {
				NewsImg newsImg = new NewsImg();
				File imageFile = this.getImage()[i];
				newsImg.setImg(Public.getByte(imageFile));
				newsImg.setTitle(this.getImgTitle()[i]);
				newsImg.setNote(this.getImgNote()[i]);
				imgSet.add(newsImg);
			}
		}
		news.setNewsImgs(imgSet);
		news.setLastModified(this.getNews().getCreateDate());
		this.getNewsService().insert(news);
		return "success";
	}

	// ===========================编辑新闻=============================================
	// 根据newsID查到对应的新闻记录
	public String findNewsByID() {
		this.setNews(this.getNewsService().findNewsByID(this.getNewsID()));
		this.imgDel = new ArrayList<Integer>();
		return "success";
	}

	// =============点击删除图片，将删除的图片ID添加到imageLeft列表========
	public String delOneImg() {
		this.imgDel.add(this.getImgID());
		return "success";
	}

	// 保存新闻的修改
	public String editNews() throws Exception {
		try {
			updateNews();
		} catch (Exception e) {
			System.out.println("保存新闻修改失败。");
			e.printStackTrace();
		} finally {
			clearIt();
		}
		return "success";
	}

	// 保存新闻的修改
	public String updateNews() throws Exception {
		// 生成新的imgSet，将需要删除的图片从set中剔除
		Set<NewsImg> oldImages = this.getNews().getNewsImgs();
		Set<NewsImg> newImages = new LinkedHashSet<NewsImg>();
		Iterator<NewsImg> i = oldImages.iterator();
		while (i.hasNext()) {
			NewsImg currentImg = (NewsImg) i.next();
			int newsImgID = currentImg.getNewsImgID();
			boolean found = false;
			for (int j = 0; j < this.getImgDel().size(); j++) {
				int imgDel = this.getImgDel().get(j);
				if (imgDel == newsImgID) {
					found = true;
					break;
				}
			}
			// 如果没有找到，那么这张图片没有删除，添加到newImages中
			if (!found) {
				newImages.add(currentImg);
			}
		}
		// 添加新的图片
		if (this.getImage() != null) {
			for (int j = 0; j < this.getImage().length; j++) {
				NewsImg newsImg = new NewsImg();
				File imageFile = this.getImage()[j];
				newsImg.setImg(Public.getByte(imageFile));
				newsImg.setTitle(this.getImgTitle()[j]);
				newsImg.setNote(this.getImgNote()[j]);
				newImages.add(newsImg);
			}
		}
		news.setNewsImgs(newImages);
		news.setLastModified(new Date());
		this.getNewsService().update(news);
		this.getNewsService().deleteOrphanItems();
		return "success";
	}

	// ===========================新闻正文修改=============================================
	// 修改新闻的正文
	public String modifyNewsContent() {
		try {
			this.getNews().setContent(this.getNewsContent());
			this.getNewsService().update(this.getNews());
		} catch (Exception e) {

		} finally {
			clearIt();
		}
		this.setResult("新闻正文内容修改成功！修改时间：" + Public.createDateTime());
		return "success";
	}

	// ===========================删除新闻=============================================
	// 删除选中的记录
	public String deleteRows() {
		String ids[] = this.getIds().split(",");
		for (int i = 0; i < ids.length; i++) {
			int id = Integer.parseInt(ids[i]);
			// this.deleteNewsPics(id);
			this.getNewsService().delete(id);
		}
		return "success";
	}

	// 操作完成之后，将相关变量的值清空
	private void clearIt() {
		this.setImage(null);
		this.setNews(null);
		this.setNewsContent(null);
	}

	// ===========================新闻列表=============================================
	// 初始化页面的时候需要初始化的一些设定值
	public void loadOptions() {
		// 获取每页显示的记录数
		String setValue = this.getSettingsService().getOption("Options", "rowCountPerPage");
		this.setRowCountPerPage(Integer.parseInt(setValue));
		// 分页工具条最多显示的页面数
		setValue = this.getSettingsService().getOption("Options", "maxPageInBar");
		this.setMaxPageInBar(Integer.parseInt(setValue));
	}

	// 按条件查询，得到新闻列表
	public String queryNewsList() {
		loadOptions();
		// 总共的记录数
		int count = this.getNewsService().getNewsCount();
		// 初始化分页工具栏的参数
		this.getPageService().initParams(count, this.pageNo, this.rowCountPerPage, this.maxPageInBar);
		// 生成分页工具栏
		this.setPageBar(this.getPageService().createPageBar());
		// 根据输入的sql查询当前页的记录
		this.setNewsList(this.getNewsService().getNewsTitle(this.getPageService().getFirstItemThisPage(), this.rowCountPerPage));
		return "success";
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public int getRowCountPerPage() {
		return rowCountPerPage;
	}

	public void setRowCountPerPage(int rowCountPerPage) {
		this.rowCountPerPage = rowCountPerPage;
	}

	public int getMaxPageInBar() {
		return maxPageInBar;
	}

	public void setMaxPageInBar(int maxPageInBar) {
		this.maxPageInBar = maxPageInBar;
	}

	public String getPageBar() {
		return pageBar;
	}

	public void setPageBar(String pageBar) {
		this.pageBar = pageBar;
	}

	public List<Object> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<Object> newsList) {
		this.newsList = newsList;
	}

	public int getPageNo() {
		return pageNo;
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public int getNewsID() {
		return newsID;
	}

	public void setNewsID(int newsID) {
		this.newsID = newsID;
	}

	public File[] getImage() {
		return image;
	}

	public void setImage(File[] image) {
		this.image = image;
	}

	public String getRte() {
		return rte;
	}

	public void setRte(String rte) {
		this.rte = rte;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public InputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(InputStream imageStream) {
		this.imageStream = imageStream;
	}

	public int getImgID() {
		return imgID;
	}

	public void setImgID(int imgID) {
		this.imgID = imgID;
	}

	public String[] getImgTitle() {
		return imgTitle;
	}

	public void setImgTitle(String[] imgTitle) {
		this.imgTitle = imgTitle;
	}

	public String[] getImgNote() {
		return imgNote;
	}

	public void setImgNote(String[] imgNote) {
		this.imgNote = imgNote;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public List<Integer> getImgDel() {
		return imgDel;
	}

	public void setImgDel(List<Integer> imgDel) {
		this.imgDel = imgDel;
	}

	public String getNewsContent() {
		return newsContent;
	}

	public void setNewsContent(String newsContent) {
		this.newsContent = newsContent;
	}

}
